/*----------------------------------------------------------------------------------------------
 *
 * This file is XIU's property. It contains XIU's trade secret, proprietary and
 * confidential information.
 *
 * The information and code contained in this file is only for authorized XIU employees
 * to design, create, modify, or review.
 *
 * DO NOT DISTRIBUTE, DO NOT DUPLICATE OR TRANSMIT IN ANY FORM WITHOUT PROPER AUTHORIZATION.
 *
 * If you are not an intended recipient of this file, you must not copy, distribute, modify,
 * or take any action in reliance on it.
 *
 * If you have received this file in error, please immediately notify XIU and
 * permanently delete the original and any copy of any file and any printout thereof.
 * (c) www.xiusdk.cn
 *---------------------------------------------------------------------------------------------*/

#import "SimpleDataPicker.h"

@interface SimpleDataPicker()
{
    NSArray* _list;
}
@end

@implementation SimpleDataPicker

-(instancetype)initWithList:(NSArray*)list
{
    self = [super init];
    if(self)
    {
        _list = [NSMutableArray arrayWithArray:list];
    }
    return self;
}

-(void)setDefaultIndex:(NSInteger)defaultIndex
{
    _defaultIndex = defaultIndex;
    if( [self.pickerViewController.pickerView numberOfRowsInComponent:0] > 0 )
    {
        [self.pickerViewController.pickerView selectRow:defaultIndex inComponent:0 animated:NO];
        [self.pickerViewController.pickerView performSelector:@selector(reloadAllComponents) withObject:nil afterDelay:0.2];
    }
}

-(void)presentWithAnimated:(BOOL)animated completion:(void(^)(BOOL))completion
{
    [super presentWithAnimated:animated completion:completion];
    [self setDefaultIndex:_defaultIndex];
}

#pragma make- DataPickerViewControllerDelegate
-(BOOL)shouldDismissViewController:(DataPickerViewController*)pickerViewController
{
    NSInteger index = [pickerViewController.pickerView selectedRowInComponent:0];
    if(_delegate && [_delegate respondsToSelector:@selector(simpleDataPicker:selectedIndex:data:)])
    {
        [_delegate simpleDataPicker:self selectedIndex:index data:_list[index]];
    }
    return YES;
}

#pragma make- UIPickerViewDataSource
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _list.count;
}

#pragma make- UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    id item = _list[row];
    if([item isKindOfClass:[NSString class]])
    {
        return item;
    }
    else
    {
        return [NSString stringWithFormat:@"%@", item];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    [super pickerView:pickerView didSelectRow:row inComponent:component];
}
@end
